﻿using HW.Application.Initialize.Models;
using HW.Core.Ioc;
using HW.Logger;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media.Media3D;

namespace HW.Application.Initialize.Services
{
    /// <summary>
    /// 硬件生命周期管理器
    /// </summary>
    [ExposedService(Lifetime.Singleton)]
    public class HardwareLifetimeManager
    {
        /// <summary>
        /// 表示所有硬件加载成功
        /// </summary>
        public bool IsInitialized { get; set; }

        public HardwareLifetimeManager()
        {
        }

        public async Task<InitResult> InitAsync()
        {
            if (IsInitialized)
            {
                throw new Exception("重复初始化硬件");
            }

            Task<bool> task1 = Task.Run(() => 1 == 1);
            
            Task<bool> task2 = Task.Run(() => 1 == 1);
          
            var list = await Task.WhenAll(task1, task2);

            bool result = list.All(p => p);

            if (!result)
            {
                string msg = "硬件初始化失败";
                if (task1.Result == false)
                    msg += "硬件1|";
                if (task2.Result == false)
                    msg += "硬件2|";
                msg = msg.Remove(msg.Length - 1);

                return new InitResult { Message = msg, Success = false };
            }

            IsInitialized = true;

            return new InitResult { Message = "硬件初始化成功", Success = true };

        }

        public void Close()
        {
            try
            {

            }
            catch (Exception ex)
            {
                Logs.LogError(ex);
            }
        }
    }
}
